package com.wingsoft.work.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wingsoft.basic.domain.SoraConfig;
import com.wingsoft.common.exception.ServiceException;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import com.wingsoft.common.utils.SecurityUtils;
import com.wingsoft.work.domain.UserTaskLog;
import com.wingsoft.work.domain.UserVip;
import com.wingsoft.work.dto.SimpleTask;
import com.wingsoft.work.vo.UserVipVo;
import okhttp3.OkHttpClient;
import org.apache.commons.lang3.ObjectUtils;
import com.wingsoft.common.utils.bean.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wingsoft.work.mapper.UserTaskMapper;
import com.wingsoft.work.domain.UserTask;
import com.wingsoft.work.service.IUserTaskService;
import com.wingsoft.common.utils.IdGenerator.IdGeneratorFactory;
import com.wingsoft.work.dto.UserTaskDto;
import com.wingsoft.work.vo.UserTaskVo;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;

import java.util.stream.Collectors;

/**
 * 用户任务Service业务层处理
 *
 * @author hemj
 * @date 2025-10-20
 */
@Service
public class UserTaskServiceImpl extends MPJBaseServiceImpl<UserTaskMapper, UserTask> implements IUserTaskService
{
    @Autowired
    private IdGeneratorFactory idGeneratorFactory;
    @Autowired
    private UserVipServiceImpl userVipService;
    @Autowired
    private UserTaskLogServiceImpl userTaskLogService;

    /**
         * 验证参数
         */
    private void validateData(UserTask userTask){
        if (ObjectUtils.isEmpty(userTask.getTaskType())){
            throw new ServiceException("任务类型不能为空");
        }
        if (userTask.getTaskType() == 2){
            if (ObjectUtils.isEmpty(userTask.getPicUrl())){
                throw new ServiceException("请上传图片");
            }
        }
        if (ObjectUtils.isEmpty(userTask.getDes())){
            throw new ServiceException("视频描述不能为空");
        }
        if (ObjectUtils.isEmpty(userTask.getVideoType())){
            throw new ServiceException("画面模式不能为空");
        }
        if (ObjectUtils.isEmpty(userTask.getSeconds())){
            throw new ServiceException("视频时间不能为空");
        }
        if (userTask.getSeconds() != 10 && userTask.getSeconds() != 15){
            throw new ServiceException("视频时间不合法！");
        }
    }

    @Transactional(timeout = 3000, isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED)
    public UserTask addTaskBatch(UserTaskDto userTaskDto) {
        if (ObjectUtils.isEmpty(userTaskDto.getTaskType())){
            throw new ServiceException("任务类型不能为空");
        }
        if (ObjectUtils.isEmpty(userTaskDto.getVideoType())){
            throw new ServiceException("画面模式不能为空");
        }
        if (ObjectUtils.isEmpty(userTaskDto.getSeconds())){
            throw new ServiceException("视频时间不能为空");
        }
        if (userTaskDto.getSeconds() != 10 && userTaskDto.getSeconds() != 15){
            throw new ServiceException("视频时间不合法！");
        }
        List<SimpleTask> simpleTaskList = userTaskDto.getSimpleTaskList();
        if (ObjectUtils.isEmpty(simpleTaskList)){
            throw new ServiceException("请传入任务列表！");
        }
        //校验是否合法
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<UserVip> vipWrapper = new LambdaQueryWrapper<>();
        vipWrapper.eq(UserVip::getUserId, userId);
        UserVip userVip = userVipService.getOne(vipWrapper,false);
        if (ObjectUtils.isEmpty(userVip)) {
            throw new ServiceException("您还不是vip！");
        }
        if (userVip.getStatus() != 1){
            throw new ServiceException("您的VIP已经过期或失效！");
        }


        userVip.setPointNum(userVip.getPointNum().subtract(new BigDecimal(simpleTaskList.size())));
        if (userVip.getPointNum().compareTo(BigDecimal.ZERO) < 0){
            throw new ServiceException("您的积分已经不足！");
        }
        userVipService.updateById(userVip);


        List<UserTask> userTasks = new ArrayList<>();
        List<UserTaskLog> userTaskLogs = new ArrayList<>();
        for (SimpleTask simpleTask : simpleTaskList){
            UserTask userTask = new UserTask();
            BeanUtils.copyProperties(userTaskDto,userTask);

            userTask.setPicUrl(simpleTask.getPicUrl());
            userTask.setDes(simpleTask.getDes());
            userTask.setCostPoint(BigDecimal.ONE);
            userTask.setStatus(0);
            userTask.setUserId(userId);
            userTask.setId(idGeneratorFactory.getId(UserTask.class.getSimpleName()));
            userTasks.add(userTask);

            UserTaskLog userTaskLog = new UserTaskLog();
            userTaskLog.setUserId(userId);
            userTaskLog.setDes("新建任务！");
            userTaskLog.setTaskId(userTask.getId());
            userTaskLog.setId(idGeneratorFactory.getId(UserTaskLog.class));
            userTaskLog.setCreateBy(userTask.getCreateBy());
            userTaskLog.setCreateTime(new Date());
            userTaskLogs.add(userTaskLog);
        }
        this.saveBatch(userTasks);
        userTaskLogService.saveBatch(userTaskLogs);
        return userTasks.get(0);
    }


    /**
     * 保存数据
     */
    @Transactional(timeout = 3000, isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED)
    public UserTask saveCascade(UserTaskDto userTaskDto){
        UserTask userTask = new UserTask();
        BeanUtils.copyProperties(userTaskDto,userTask);
        validateData(userTask);
        //校验是否合法
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<UserVip> vipWrapper = new LambdaQueryWrapper<>();
        vipWrapper.eq(UserVip::getUserId, userId);
        UserVip userVip = userVipService.getOne(vipWrapper,false);
        if (ObjectUtils.isEmpty(userVip)) {
            throw new ServiceException("您还不是vip！");
        }
        if (userVip.getStatus() != 1){
            throw new ServiceException("您的VIP已经过期或失效！");
        }
        userVip.setPointNum(userVip.getPointNum().subtract(new BigDecimal(1)));
        if (userVip.getPointNum().compareTo(BigDecimal.ZERO) < 0){
            throw new ServiceException("您的积分已经不足！");
        }
        userVipService.updateById(userVip);

        userTask.setCostPoint(BigDecimal.ONE);
        userTask.setStatus(0);
        userTask.setUserId(userId);
        userTask.setId(idGeneratorFactory.getId(UserTask.class.getSimpleName()));
        this.save(userTask);

        userTaskLogService.saveByTask(userTask,"新建视频任务！","");


        return userTask;
    }



    /**
     * 使用Stream API添加type
     */
    public static String addInterfaceTypeStream(String hisInterfaceType, String newType) {
        if (newType == null || newType.trim().isEmpty()) {
            return hisInterfaceType == null ? "" : hisInterfaceType;
        }

        String trimmedNewType = newType.trim();

        if (hisInterfaceType == null || hisInterfaceType.trim().isEmpty()) {
            return trimmedNewType;
        }

        String trimmedHisType = hisInterfaceType.trim();

        // 使用Stream处理分割、去重和拼接[2,8](@ref)
        String result = Arrays.stream(trimmedHisType.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.joining(","));

        // 检查是否已存在
        boolean exists = Arrays.stream(result.split(","))
                .anyMatch(type -> type.equals(trimmedNewType));

        if (exists) {
            return result;
        } else {
            return result.isEmpty() ? trimmedNewType : result + "," + trimmedNewType;
        }
    }
    /**
     * 编辑数据
     */
    @Transactional(timeout = 3000, isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED)
    public UserTask updateCascade(UserTaskDto userTaskDto){
        UserTask userTask = this.getById(userTaskDto.getId());;
        BeanUtils.copyPropertiesIgnoreNull(userTaskDto,userTask);
        validateData(userTask);
        this.updateById(userTask);
        return userTask;
    }

    /**
     * 初始化查询条件
     */
    public MPJLambdaWrapper<UserTask> initQueryWrapper(UserTaskDto userTaskDto){
        MPJLambdaWrapper<UserTask> queryWrapper = new MPJLambdaWrapper<>();
        if (!ObjectUtils.isEmpty(userTaskDto.getUserId())) {
            queryWrapper.eq(UserTask::getUserId, userTaskDto.getUserId());
        }
        if (!ObjectUtils.isEmpty(userTaskDto.getCreateBy())) {
            queryWrapper.like(UserTask::getCreateBy, userTaskDto.getCreateBy());
        }
        if (!ObjectUtils.isEmpty(userTaskDto.getTaskId())) {
            queryWrapper.eq(UserTask::getTaskId, userTaskDto.getTaskId());
        }
        if (!ObjectUtils.isEmpty(userTaskDto.getTaskType())) {
            queryWrapper.eq(UserTask::getTaskType, userTaskDto.getTaskType());
        }
        if (!ObjectUtils.isEmpty(userTaskDto.getPicUrl())) {
            queryWrapper.eq(UserTask::getPicUrl, userTaskDto.getPicUrl());
        }
        if (!ObjectUtils.isEmpty(userTaskDto.getDes())) {
            queryWrapper.eq(UserTask::getDes, userTaskDto.getDes());
        }
        if (!ObjectUtils.isEmpty(userTaskDto.getVideoType())) {
            queryWrapper.eq(UserTask::getVideoType, userTaskDto.getVideoType());
        }
        if (!ObjectUtils.isEmpty(userTaskDto.getCostPoint())) {
            queryWrapper.eq(UserTask::getCostPoint, userTaskDto.getCostPoint());
        }
        if (!ObjectUtils.isEmpty(userTaskDto.getDelFlag())) {
            queryWrapper.eq(UserTask::getDelFlag, userTaskDto.getDelFlag());
        }
        if (!ObjectUtils.isEmpty(userTaskDto.getStatus())) {
            queryWrapper.eq(UserTask::getStatus, userTaskDto.getStatus());
        }
        if (!ObjectUtils.isEmpty(userTaskDto.getVideoUrl())) {
            queryWrapper.eq(UserTask::getVideoUrl, userTaskDto.getVideoUrl());
        }
        if (!ObjectUtils.isEmpty(userTaskDto.getFailMsg())) {
            queryWrapper.eq(UserTask::getFailMsg, userTaskDto.getFailMsg());
        }
        queryWrapper.orderByDesc(UserTask::getId);
        return queryWrapper;
    }

    /**
     * list查询
     */
    public List<UserTaskVo> queryList(UserTaskDto userTaskDto) {
        List<UserTask> userTasks = this.selectJoinList(UserTask.class,initQueryWrapper(userTaskDto));
        List<UserTaskVo> vos = new ArrayList<>();
        for (UserTask userTask:userTasks) {
            UserTaskVo userTaskVo = new UserTaskVo();
            BeanUtils.copyProperties(userTask,userTaskVo);
            vos.add(userTaskVo);
        }
        return vos;
    }

    /**
     * 统计
     */
    public long countList(UserTaskDto userTaskDto) {
        return this.count(initQueryWrapper(userTaskDto));
    }

    /**
     * 获取单个数据
     */
    public UserTaskVo getOneById(Long id){
        UserTask userTask = this.getById(id);
        UserTaskVo userTaskVo = new UserTaskVo();
        BeanUtils.copyProperties(userTask,userTaskVo);
        return userTaskVo;
    }

    /**
     * 删除数据
     * @param ids
     */
    @Transactional(timeout = 3000, isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED)
    public void removeByIdList(List<Long> ids) {
        this.removeByIds(ids);
    }

    @Transactional(timeout = 3000, isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED)
    public void doTaskV1(UserTask userTask,SoraConfig soraConfig){
        //发送请求
        Map<String,Object> params = new HashMap<>();
        params.put("prompt",userTask.getDes());
        System.setProperty("https.protocols", "TLSv1.2");
        String url = "https://" +soraConfig.getType()+"/v2/videos/generations";
        if (userTask.getTaskType() == 2){
            List<String> images = new ArrayList<>();
            images.add(userTask.getPicUrl());
            params.put("images",images);
        }
        params.put("duration",userTask.getSeconds());
        if (userTask.getVideoType() == 1 || userTask.getVideoType() == 3){
            params.put("aspect_ratio","16:9");
        }else {
            params.put("aspect_ratio","9:16");
        }
        params.put("hd","false");
        params.put("watermark","false");
        params.put("model","sora-2");
        // 发送请求
        String result = "";
        try {
            result = HttpUtil.createPost(url)
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer "+soraConfig.getAppkey())
                    .body(JSONUtil.toJsonStr(params))
                    .timeout(30000)
                    .execute()
                    .body();
            userTask.setApijson(result);
            JSONObject jsonObject = JSONUtil.parseObj(result);

            String taskId = jsonObject.getStr("task_id");
            if (!ObjectUtils.isEmpty(taskId)){
                userTask.setTaskId(taskId);
                userTask.setStatus(1);
                userTask.setStartTime(new Date());
                userTask.setNowInterfaceType(soraConfig.getType());
                userTaskLogService.saveByTask(userTask,"调用视频生成",result);

                //接口请求后记录历史请求接口类型。
                userTask.setHisInterfaceType(addInterfaceTypeStream(userTask.getHisInterfaceType(),soraConfig.getType()));
                this.updateById(userTask);
            }else {
                throw new ServiceException("接口调用有误，切换下一个接口！");
            }
        } catch (Exception e) {
            userTask.setHisInterfaceType(addInterfaceTypeStream(userTask.getHisInterfaceType(),soraConfig.getType()));
            taskFail(userTask,"创建超时，切换下一接口",result);
        }

    }

    @Transactional(timeout = 3000, isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED)
    public void getTaskV1(UserTask userTask,SoraConfig soraConfig) {
        String url = "https://" +soraConfig.getType()+"/v2/videos/generations/"+userTask.getTaskId();
        // 发送请求
        String result = "";
        try {
            result = HttpUtil.createGet(url)
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer "+soraConfig.getAppkey())
                    .timeout(30000)
                    .execute()
                    .body();
        }catch (Exception e){
            if (this.isMoreThanMinutes(userTask.getStartTime(),10)){
                taskFail(userTask,"获取信息失败，切换下一接口","");
                return;
            }else {
                throw new ServiceException("访问超时，继续等待！");
            }
        }
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String status = jsonObject.getStr("status");
        if (ObjectUtils.isEmpty(status)){
            if (this.isMoreThanMinutes(userTask.getStartTime(),10)){
                taskFail(userTask,"获取信息失败，切换下一接口","");
                return;
            }
        }
        if (status.equals("FAILURE")){
            String fail_reason = jsonObject.getStr("fail_reason");
            this.taskFail(userTask,fail_reason,result);
        }else if (status.equals("SUCCESS")){
            JSONObject data = jsonObject.getJSONObject("data");
            String output = data.getStr("output");
            this.taskSuccess(userTask,output,result);
        }

    }

    @Transactional(timeout = 3000, isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED)
    public void doTaskV2(UserTask userTask,SoraConfig soraConfig) {
        //发送请求
        Map<String,Object> params = new HashMap<>();
        params.put("prompt",userTask.getDes());
        String url = "https://" +soraConfig.getType()+"/v1/videos";
        if (userTask.getTaskType() == 2){
            params.put("image_url",userTask.getPicUrl());
        }
        if (userTask.getVideoType() == 1 || userTask.getVideoType() == 3){
            if (userTask.getSeconds() == 10){
                params.put("model","sora2-landscape");
            }else {
                params.put("model","sora2-landscape-15s");
            }
        }else {
            if (userTask.getSeconds() == 10){
                params.put("model","sora2-portrait");
            }else {
                params.put("model","sora2-portrait-15s");
            }
        }
        // 发送请求
        String result = "";
        try {
            result = HttpUtil.createPost(url)
                    .header("Accept", "application/json")
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer "+soraConfig.getAppkey())
                    .body(JSONUtil.toJsonStr(params))
                    .timeout(30000)
                    .execute()
                    .body();
            userTask.setApijson(result);
            JSONObject jsonObject = JSONUtil.parseObj(result);
            String taskId = jsonObject.getStr("id");
            if (!ObjectUtils.isEmpty(taskId)){
                userTask.setTaskId(taskId);
                userTask.setStatus(1);
                userTask.setStartTime(new Date());
                userTask.setNowInterfaceType(soraConfig.getType());
                userTaskLogService.saveByTask(userTask,"调用视频生成",result);
                //接口请求后记录历史请求接口类型。
                userTask.setHisInterfaceType(addInterfaceTypeStream(userTask.getHisInterfaceType(),soraConfig.getType()));
                this.updateById(userTask);
            }else {
                throw new ServiceException("接口调用有误，切换下一个接口！");
            }
        } catch (Exception e) {
            userTask.setHisInterfaceType(addInterfaceTypeStream(userTask.getHisInterfaceType(),soraConfig.getType()));
            taskFail(userTask,"创建超时，切换下一接口",result);
        }
    }



    @Transactional(timeout = 3000, isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED)
    public void getTaskV2(UserTask userTask,SoraConfig soraConfig) {
        String url = "https://" +soraConfig.getType()+"/v1/videos/"+userTask.getTaskId();
        // 发送请求
        String result = "";
        try {
            result = HttpUtil.createGet(url)
                    .header("Accept", "application/json")
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer "+soraConfig.getAppkey())
                    .timeout(30000)
                    .execute()
                    .body();
        }catch (Exception e){
            if (this.isMoreThanMinutes(userTask.getStartTime(),10)){
                taskFail(userTask,"获取信息失败，切换下一接口","");
                return;
            }else {
                throw new ServiceException("访问超时，继续等待！");
            }
        }

        JSONObject jsonObject = JSONUtil.parseObj(result);
        String status = jsonObject.getStr("status");
        if (ObjectUtils.isEmpty(status)){
            if (this.isMoreThanMinutes(userTask.getStartTime(),10)){
                taskFail(userTask,"获取信息失败，切换下一接口","");
                return;
            }
        }
        if (status.equals("failed")){
            String fail_reason = jsonObject.getStr("fail_reason");
            this.taskFail(userTask,fail_reason,result);
        }else if (status.equals("completed")){
            String videoUrl = jsonObject.getStr("video_url");
            this.taskSuccess(userTask,videoUrl,result);
        }
    }



    @Transactional(timeout = 3000, isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED)
    public void doTaskV3(UserTask userTask,SoraConfig soraConfig) {
        //发送请求
        Map<String,Object> params = new HashMap<>();
        params.put("prompt",userTask.getDes());
        String url = "https://" +soraConfig.getType()+"/v1/video/create";
        if (userTask.getTaskType() == 2){
            List<String> images = new ArrayList<>();
            images.add(userTask.getPicUrl());
            params.put("images",images);
        }
        if (userTask.getVideoType() == 1 || userTask.getVideoType() == 3){
            params.put("orientation","landscape");
        }else {
            params.put("orientation","portrait");
        }
        params.put("size","small");
        params.put("duration",userTask.getSeconds());
        params.put("watermark","false");
        params.put("model","sora-2");

        // 发送请求
        String result = "";
        try {
            result = HttpUtil.createPost(url)
                    .header("Accept", "application/json")
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer "+soraConfig.getAppkey())
                    .body(JSONUtil.toJsonStr(params))
                    .timeout(30000)
                    .execute()
                    .body();
            userTask.setApijson(result);
            JSONObject jsonObject = JSONUtil.parseObj(result);
            String taskId = jsonObject.getStr("id");
            if (!ObjectUtils.isEmpty(taskId)){
                userTask.setTaskId(taskId);
                userTask.setStatus(1);
                userTask.setNowInterfaceType(soraConfig.getType());
                userTask.setStartTime(new Date());
                userTaskLogService.saveByTask(userTask,"调用视频生成",result);
                //接口请求后记录历史请求接口类型。
                userTask.setHisInterfaceType(addInterfaceTypeStream(userTask.getHisInterfaceType(),soraConfig.getType()));
                this.updateById(userTask);
            }else {
                throw new ServiceException("接口调用有误，切换下一个接口！");
            }
        } catch (Exception e) {
            userTask.setHisInterfaceType(addInterfaceTypeStream(userTask.getHisInterfaceType(),soraConfig.getType()));
            taskFail(userTask,"创建超时，切换下一接口",result);
        }
    }



    @Transactional(timeout = 3000, isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED)
    public void getTaskV3(UserTask userTask,SoraConfig soraConfig) {
        String url = "https://" +soraConfig.getType()+"/v1/video/query?id="+userTask.getTaskId();

        String result = "";
        try {
            result = HttpUtil.createGet(url)
                    .header("Accept", "application/json")
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer "+soraConfig.getAppkey())
                    .timeout(30000)
                    .execute()
                    .body();
        }catch (Exception e){
            if (this.isMoreThanMinutes(userTask.getStartTime(),10)){
                taskFail(userTask,"获取信息失败，切换下一接口","");
                return;
            }else {
                throw new ServiceException("访问超时，继续等待！");
            }
        }

        JSONObject jsonObject = JSONUtil.parseObj(result);
        String status = jsonObject.getStr("status");
        if (ObjectUtils.isEmpty(status)){
            if (this.isMoreThanMinutes(userTask.getStartTime(),10)){
                taskFail(userTask,"获取信息失败，切换下一接口","");
                return;
            }
        }
        if (status.equals("failed")){
            String fail_reason = jsonObject.getStr("fail_reason");
            this.taskFail(userTask,fail_reason,result);
        }else if (status.equals("completed")){
            String videoUrl = jsonObject.getStr("video_url");
            this.taskSuccess(userTask,videoUrl,result);
        }
    }


    public void taskFail(UserTask userTask,String failReason,String result){
        userTask.setFailMsg(failReason);
        userTask.setStatus(0);
        userTask.setApijson(result);
        this.updateById(userTask);

        userTaskLogService.saveByTask(userTask,"任务执行失败："+failReason+"。",result);
    }

    public void taskSuccess(UserTask userTask,String videoUrl,String result){
        userTask.setStatus(2);
        userTask.setVideoUrl(videoUrl);
        userTask.setUpdateTime(new Date());
        userTask.setFinishTime(LocalDateTime.now());
        userTask.setApijson(result);
        userTask.setHisInterfaceType(addInterfaceTypeStream(userTask.getHisInterfaceType(),userTask.getNowInterfaceType()));
        userTask.setOssStatus(1);
        userTask.setOssTime(0);

        userTaskLogService.saveByTask(userTask,"任务执行成功。",result);
        this.updateById(userTask);

    }

    public void deleteTask(Long id) {
        if (ObjectUtils.isEmpty(id)){
            throw new ServiceException("id必传");
        }
        LambdaUpdateWrapper<UserTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserTask::getId, id);
        updateWrapper.set(UserTask::getDelFlag, 1);
        this.update(updateWrapper);
    }


    @Transactional
    public void taskFinalFail(UserTask userTask) {
        userTaskLogService.saveByTask(userTask,"轮询结束，未获得成功任务","");

        LambdaQueryWrapper<UserVip> vipWrapper = new LambdaQueryWrapper<>();
        vipWrapper.eq(UserVip::getUserId, userTask.getUserId());
        UserVip userVip = userVipService.getOne(vipWrapper,false);
        if (ObjectUtils.isEmpty(userVip)) {
            userVip.setPointNum(userVip.getPointNum().add(userTask.getCostPoint()));
            userVipService.updateById(userVip);
        }

        userTask.setStatus(3);
        userTask.setFinishTime(LocalDateTime.now());
        this.updateById(userTask);
    }

    public boolean isMoreThanMinutes(Date createTime,Integer minutes) {
        if (ObjectUtils.isEmpty(createTime)) {
            createTime = new Date();
        }
        // 1. 获取当前时间和创建时间的毫秒数
        long currentTimeMillis = System.currentTimeMillis();
        long createTimeMillis = createTime.getTime();


        // 2. 计算毫秒差的绝对值
        long diffInMillies = Math.abs(currentTimeMillis - createTimeMillis);

        // 3. 将毫秒差与2分钟（120000毫秒）比较
        return diffInMillies > minutes * 60 * 1000; // 120 * 1000 = 120000
    }

    public String downloadVideo(UserTaskDto userTaskDto) {
        UserTask userTask = this.getById(userTaskDto.getId());
        String videoUrl = userTask.getVideoUrl();
        if (ObjectUtils.isEmpty(videoUrl)) {
            throw new ServiceException("视频还未生成，请耐心等待！");
        }
        Map<String,Object> params = new HashMap<>();
        params.put("videoUrl",videoUrl);
        params.put("taskId",userTask.getTaskId());
        String time = System.currentTimeMillis()+"";
        params.put("timestamp",time);
        String key = "basic@abc@123456";
        String md5Pre = time+key;
        String checkedStr = DigestUtil.md5Hex(md5Pre);
        params.put("checkedStr", checkedStr);
        // 发送请求

        try {
            String result = HttpUtil.createPost("http://47.242.202.240:8080/process_video")
                    .header("Content-Type", "application/json")
                    .body(JSONUtil.toJsonStr(params))
                    .timeout(30000)
                    .execute()
                    .body();
            JSONObject jsonObject = JSONUtil.parseObj(result);
            String status = jsonObject.getStr("status");
            if (!ObjectUtils.isEmpty(status) && status.equals("success")){
                return jsonObject.getStr("ossUrl");
            }else {
                if (ObjectUtils.isEmpty(jsonObject.getStr("message"))){
                    return jsonObject.getStr("error");
                }
                return jsonObject.getStr("message");
            }
        } catch (Exception e) {
            throw new ServiceException("接口访问超时");
        }
    }
}
